/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model.newmodel;

import services.Stemmer;
import services.StopWords;

/**
 * 
 * @author i_khri
 */
public class Term implements Comparable<Term> {

	/**
	 * 
	 * @param token
	 *            the string to tokenize to terms
	 * @return the term obtained from the string
	 * @throws model.newmodel.InvalidTermException
	 */
	public static Term newInstance(String token) throws InvalidTermException {
		Term term = new Term(token);
		if (term.termStr.isEmpty()) {
			term = null;
			throw new InvalidTermException("Token " + token
					+ " cannot be transformed to a valid token.");
		} else {
			return term;
		}
	}

	/**
	 * This is to extract the terms from the index files
	 * 
	 * @param theString
	 *            the index
	 * @return the term
	 */
	public static Term fromIndexString(String theString) {
		int beginIndex = theString.indexOf('[');
		return new Term(theString.substring(0, beginIndex));
	}

	/**
	 * 
	 * @return the wanted term
	 */
	public String getTerm() {
		return termStr;
	}

	/**
	 * 
	 * @return the hash code
	 */
	@Override
	public int hashCode() {
		int hash = 7;
		hash = 11 * hash + (this.termStr != null ? this.termStr.hashCode() : 0);
		return hash;
	}

	/**
	 * 
	 * @param obj
	 *            the object to compare
	 * @return either true or false if they are the same or not
	 */
	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final Term other = (Term) obj;
		if ((this.termStr == null) ? (other.termStr != null) : !this.termStr
				.equals(other.termStr)) {
			return false;
		}
		return true;
	}

	/**
	 * @return the term as a string
	 */
	@Override
	public String toString() {
		return termStr;
	}

	/**
	 * 
	 * @param o
	 *            the term object to compare
	 * @return the comparison
	 */
	public int compareTo(Term o) {
		return termStr.compareTo(o.termStr);
	}

	/**
	 * @param token
	 *            the token to stem and treat before doing anything else with it
	 */
	private Term(String token) {
		token = token.trim().toLowerCase();

		if (token.length() >= 2 && !StopWords.contains(token)) {
			// Stemming the tokens
			this.termStr = token;
			/*
			 * Stemmer stemmer = new Stemmer(); stemmer.add(token.toCharArray(),
			 * token.toCharArray().length); stemmer.stem(); this.termStr =
			 * stemmer.toString();
			 */
		} else {
			this.termStr = "";
		}
	}

	private String termStr;

}
